<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

import { SearchOutlined } from '@ant-design/icons-vue';
import {
  Button as AButton, // 导入 Button 用于筛选
  Input as AInput, // 导入 Input 用于筛选
  Modal as AModal,
  Spin as ASpin,
  Table as ATable,
  TableSummary as ATableSummary,
  TableSummaryCell as ATableSummaryCell,
  TableSummaryRow as ATableSummaryRow,
} from 'ant-design-vue';

// 确保API路径正确
import { getHomeDataDetail } from '#/api/hm/home/index.ts';

// --- 组件通信 (Props & Emits) ---
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '查看详情',
  },
  params: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:visible']);

// --- 状态管理 ---
const loading = ref(false);
const tableData = ref([]);
const totalAmount = ref(0);

// 1. 新增：将分页配置变为响应式对象
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  hideOnSinglePage: true,
});

// 2. 新增：筛选状态管理
const searchInput = ref();
const state = reactive({
  searchText: '',
  searchedColumn: '',
});

// --- 表格列定义 (修改为计算属性以支持动态筛选) ---
const tableColumns = computed(() => [
  {
    title: '序号',
    key: 'index',
    width: 60,
    align: 'center',
    customRender: ({ index }) =>
      `${(pagination.current - 1) * pagination.pageSize + index + 1}`,
  },
  {
    title: '订单ID',
    dataIndex: 'saleOrderId',
    key: 'saleOrderId',
    width: 200,
    // 2. 新增：订单ID筛选功能
    customFilterDropdown: true,
    onFilter: (value, record) =>
      record.saleOrderId.toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => {
          searchInput.value.focus();
        }, 100);
      }
    },
  },
  {
    title: '客户名称',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 150,
    // 2. 新增：客户名称筛选功能
    filters: [...new Set(tableData.value.map((item) => item.customerName))].map(
      (name) => ({ text: name, value: name }),
    ),
    onFilter: (value, record) => record.customerName.indexOf(value) === 0,
  },
  {
    title: '产品名称',
    dataIndex: 'saleProductName',
    key: 'saleProductName',
  },
  {
    title: '回款金额',
    dataIndex: 'pickUpNum',
    key: 'pickUpNum',
    width: 150,
    align: 'right',
  },
  {
    title: '回款时间',
    dataIndex: 'pickUpTime',
    key: 'pickUpTime',
    width: 180,
  },
]);

// --- 核心方法 ---

// 获取数据的函数
async function fetchData(queryParams) {
  if (!queryParams || Object.keys(queryParams).length === 0) {
    tableData.value = [];
    return;
  }
  loading.value = true;
  try {
    const res = await getHomeDataDetail({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    if (res.list?.code === 200) {
      tableData.value = res.list.rows || [];
      pagination.total = res.list.total || 0;
      totalAmount.value = res.totalAmount || 0;
    } else {
      tableData.value = [];
      pagination.total = 0;
      totalAmount.value = 0;
    }
  } catch (error) {
    console.error('获取详情数据失败:', error);
    tableData.value = [];
    pagination.total = 0;
    totalAmount.value = 0;
  } finally {
    loading.value = false;
  }
}

// 1. 新增：处理表格变化（分页、筛选）的函数
function handleTableChange(page) {
  pagination.current = page.current;
  pagination.pageSize = page.pageSize;
  fetchData(props.params);
}

// 2. 新增：处理筛选搜索和重置的函数
const handleSearch = (selectedKeys, confirm, dataIndex) => {
  confirm();
  state.searchText = selectedKeys[0];
  state.searchedColumn = dataIndex;
};

const handleReset = (clearFilters) => {
  clearFilters({ confirm: true });
  state.searchText = '';
};

// 监听 visible 属性，当其变为 true 时获取数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.params) {
      // 重置分页到第一页
      pagination.current = 1;
      fetchData(props.params);
    }
  },
);

// 处理弹窗关闭事件
function handleCancel() {
  emit('update:visible', false);
}
</script>

<template>
  <AModal
    :visible="visible"
    :title="title"
    @cancel="handleCancel"
    :footer="null"
    width="950px"
    destroy-on-close
  >
    <ASpin :spinning="loading">
      <ATable
        :columns="tableColumns"
        :data-source="tableData"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ y: 500 }"
        row-key="saleOrderId"
        size="small"
      >
        <template
          #customFilterDropdown="{
            setSelectedKeys,
            selectedKeys,
            confirm,
            clearFilters,
            column,
          }"
        >
          <div style="padding: 8px">
            <AInput
              ref="searchInput"
              :placeholder="`搜索 ${column.title}`"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block"
              @change="
                (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
              "
              @press-enter="
                handleSearch(selectedKeys, confirm, column.dataIndex)
              "
            />
            <AButton
              type="primary"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon><SearchOutlined /></template>
              搜索
            </AButton>
            <AButton
              size="small"
              style="width: 90px"
              @click="handleReset(clearFilters)"
            >
              重置
            </AButton>
          </div>
        </template>
        <template #customFilterIcon="{ filtered }">
          <SearchOutlined
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'pickUpNum'">
            <span>¥ {{ Number(record.pickUpNum).toFixed(2) }}</span>
          </template>
        </template>

        <template #summary>
          <ATableSummary fixed>
            <ATableSummaryRow>
              <ATableSummaryCell :col-span="4" align="center">
                <strong>合计</strong>
              </ATableSummaryCell>
              <ATableSummaryCell align="right">
                <span style="font-weight: bold; color: red">
                  ¥ {{ Number(totalAmount).toFixed(2) }}
                </span>
              </ATableSummaryCell>
              <ATableSummaryCell />
            </ATableSummaryRow>
          </ATableSummary>
        </template>
      </ATable>
    </ASpin>
  </AModal>
</template>
